using System;
using System.Collections.Generic;
using Edge.Common;
using Edge.Common.ComponentModel.Notification;
using Edge.Common.Services;
using Edge.Common.Utils;
using Edge.DAL.Common;
using Edge.DAL.Managers;
using NHibernate;
using NHibernate.Expression;
using NHibernate.Type;
using Shop.Business.Domain.Catalog;
using Shop.Business.Domain.Customers;

namespace Shop.DAL.Managers
{
    class ProductManager : AbstractManager<Product, int, Customer>, IProductManager
    {
        public ICollection<Product> Find(FetchOptions fetchOptions, ProductFilter filter)
        {
            ICriteria criteria = CreateCriteria(fetchOptions);
            AddRestrictions(criteria, filter);
            return criteria.List<Product>();
        }

        public int Count(ProductFilter filter)
        {
            ICriteria criteria = CreateCriteria();
            AddRestrictions(criteria, filter);
            criteria.SetProjection(Projections.RowCount());
            return (int)criteria.List()[0];
        }

        public void SetVisibleFalse(Brand brand)
        {
            using (IDalOperation op = CreateLoadOperation())
            {
                IQuery query = Session.GetNamedQuery("SetVisibleFalse");
                query.SetParameter("brandID", brand.Id, TypeFactory.Basic("int"));
                query.UniqueResult();
                op.Commit();
            }
        }

        public void ChangeGroupForBrandArt(string brandArt, ProductGroup productGroup)
        {
            using (IDalOperation op = CreateLoadOperation())
            {
                IQuery query = Session.GetNamedQuery("ChangeGroupForBrandArt");
                query.SetParameter("brandArt", brandArt, TypeFactory.Basic("string"));
                query.SetParameter("productGroupId", productGroup.Id, TypeFactory.Basic("int"));
                query.UniqueResult();
                op.Commit();
            }
        }

        private void AddRestrictions(ICriteria criteria, ProductFilter filter)
        {
            if (filter.Group != null)
                criteria.Add(Expression.Eq("Group", filter.Group));
            if (!StringUtils.IsBlankOrNull(filter.GetText()) && !(filter.GetText().Trim().Equals("")))
            {
                criteria.Add(Expression.Disjunction()
                                 .Add(Expression.Like("Name", "%" + filter.GetText().Trim() + "%"))
                                 .Add(Expression.Like("Description", "%" + filter.GetText().Trim() + "%"))
                    );
            }
            if (!StringUtils.IsBlankOrNull(filter.BrandArt))
            {
                criteria.Add(Expression.Eq("BrandArt", filter.BrandArt));
            }
        }

    }
}